package com.cskaoyan.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {


    // 数据源
    static DataSource dataSource;


    // 初始化数据源
    static {

        Properties properties = new Properties();
        try {
            // 绝对路径的写法，不好
//            InputStream in = new FileInputStream("E:\\cskaoyan\\35workspace\\workspace_35\\druid-maven-demo\\src\\main\\resources\\druid.properties");

            // 我们在maven的项目中，需要使用类加载器去找文件的路径
            ClassLoader classLoader = DruidUtils.class.getClassLoader();

            // 类加载去找文件的时候，因为类加载是从classes文件夹开始加载的，所以会从classes文件夹下开始加载
            InputStream inputStream = classLoader.getResourceAsStream("druid/druid.properties");


//            URL url = classLoader.getResource("druid/druid.properties");
//            String path = url.getPath();
//
//            System.out.println("path:" + path);
            // /E:/cskaoyan/35workspace/workspace_35/druid-maven-demo/target/classes/druid.properties


            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    // 获取连接
    public static Connection getConnection() {

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;

    }

    public static DataSource getDataSource() {
        return dataSource;
    }
}
